<template>
    <div class="sprite-wp">
        <div class="sprite" :style="`
          background: url('${icon}');
                                    --height: ${imgH}px;
                                     --width: ${props.width}px;
                                     --positionX: -${positionX}px;
                                    --duration: ${props.duration}s;
                                    --step: ${props.step}`">
        </div>
    </div>
</template>
<script setup lang="ts">
// meta.url 引入方式
import { spritesIcons } from "./config";
import { computed, ref } from "vue";
// 使用例子: 
// <AnimateSprite :use="'carAccess'" :width="144" :height="68"  :duration="2" :step="75"/>
// <AnimateSprite :use="'doorAccess'" :width="144" :height="68"  :duration="2" :step="75"/>
const props = defineProps({
    use: {
        type: String
    },
    width: {
        type: Number,
        default: 0
    },
    height: {
        type: Number,
        default: 0
    },
    positionX: {
        type: Number,
        default: 0
    },
    duration: {
        type: Number,
        default: 2
    },
    step: {
        type: Number,
        default: 75
    }
});


//位移距离
const positionX = ref(0);
//需要的可视元素的高度
const imgH = ref(0);

const icon = computed(() => {
    if (props.use) {
        const img = new Image();
        spritesIcons.forEach(item => {
            let template = item;
            for (let key in template) {
                if (key == props.use) {
                    img.src = (<any>item)[key];
                    img.onload = () => {
                        if (img.width || img.height) {
                            positionX.value = img.width;
                            imgH.value = props.height ? props.height : img.height;
                        }
                    }
                }
            };
        });
        return img.src;
    }

});



</script>

<style lang="scss">
.sprite-wp {
    width: auto;
    height: auto;
    box-sizing: border-box;
    object-fit: fill;
    overflow: hidden;
}

.sprite {
    width: var(--width);
    height: var(--height);
    overflow: hidden;
    will-change: transform;
    background-repeat: no-repeat;
    background-position: center;
    animation: frame var(--duration) steps(var(--step)) both infinite;
}

@keyframes frame {
    0% {
        background-position: 0 0;
    }

    100% {
        background-position: var(--positionX) 0;
    }
}
</style>